<script>
export default {
  data() {
    return {
      deviceId: '22:34:50:15:15:D8',
      serviceId: '0000FFE0-0000-1000-8000-00805F9B34FB',
      characteristicId: '0000FFE2-0000-1000-8000-00805F9B34FB',
      hex: "0011223344A1023A501234567800112233445566778899"
    }
  },
  onLoad() {
    this.listenForResponse();
  },
  methods: {
    async connectAndSend() {
      try {
        await this.openBluetoothAdapter();
        await this.connectDevice();
        await this.getCharacteristics();
        await this.enableNotify();
        await this.sendHexData();
      } catch (error) {
        uni.showToast({ title: error.message, icon: 'none' });
      }
    },

    openBluetoothAdapter() {
      return new Promise((resolve, reject) => {
        uni.openBluetoothAdapter({
          success: resolve,
          fail: () => reject(new Error('请开启蓝牙功能'))
        });
      });
    },

    connectDevice() {
      return new Promise((resolve, reject) => {
        uni.createBLEConnection({
          deviceId: this.deviceId,
          success: resolve,
          fail: () => reject(new Error('设备连接失败'))
        });
      });
    },

    getCharacteristics() {
      return new Promise((resolve, reject) => {
        uni.getBLEDeviceCharacteristics({
          deviceId: this.deviceId,
          serviceId: this.serviceId,
          success: (res) => {
            const char = res.characteristics.find(c => 
              c.uuid.toUpperCase() === this.characteristicId.toUpperCase()
            );
            if (!char) return reject(new Error('未找到特征值'));
            if (!char.properties.write) reject(new Error('特征不支持写入'));
            if (!char.properties.notify && !char.properties.indicate) {
              reject(new Error('特征不支持通知'));
            }
            resolve();
          },
          fail: () => reject(new Error('获取特征失败'))
        });
      });
    },

    enableNotify() {
      return new Promise((resolve, reject) => {
        uni.notifyBLECharacteristicValueChange({
          deviceId: this.deviceId,
          serviceId: this.serviceId,
          characteristicId: this.characteristicId,
          state: true,
          success: resolve,
          fail: () => reject(new Error('启用通知失败'))
        });
      });
    },

    sendHexData() {
      const hex = this.hex.replace(/\s/g, '');
      if (hex.length % 2 !== 0) {
        return Promise.reject(new Error('HEX数据长度不正确'));
      }
      
      const buffer = new ArrayBuffer(hex.length / 2);
      const dataView = new DataView(buffer);
      for (let i = 0; i < hex.length; i += 2) {
        const byte = parseInt(hex.substr(i, 2), 16);
        dataView.setUint8(i/2, byte);
      }

      return new Promise((resolve, reject) => {
        uni.writeBLECharacteristicValue({
          deviceId: this.deviceId,
          serviceId: this.serviceId,
          characteristicId: this.characteristicId,
          value: buffer,
          success: resolve,
          fail: () => reject(new Error('数据发送失败'))
        });
      });
    },

    listenForResponse() {
      uni.onBLECharacteristicValueChange(res => {
        if (res.deviceId === this.deviceId && 
            res.serviceId === this.serviceId &&
            res.characteristicId === this.characteristicId) {
          const hexArray = [];
          const view = new DataView(res.value);
          for (let i = 0; i < view.byteLength; i++) {
            const byte = view.getUint8(i).toString(16).padStart(2, '0');
            hexArray.push(byte);
          }
          console.log('接收数据:', hexArray.join('').toUpperCase());
          uni.showToast({ title: '收到响应数据', icon: 'none' });
        }
      });
    }
  }
}
</script>

<template>
  <view>
    <button @click="connectAndSend">发送蓝牙数据</button>
  </view>
</template>

<style>
button {
  margin: 20px;
  padding: 10px;
}
</style>